/**
 * Created by hooshim on 2014-12-04.
 */

var G_grid01 = "";
var G_grid02 = "";
var G_page = 1;

$(document).ready(function() {
    fnGetSubMenus();
    fnSetCurMenu(6);
    fnGetLeftMenus('5');
    $("#_curMenu p").html("청구서");

    $("#issueDt").datepicker(G_calendar);
    $("#incomeDt").datepicker(G_calendar);

    var bodyWidth = $('body').innerWidth();
    bodyWidth = parseInt(bodyWidth,10) - 170;
    $('#_bodyRight').css('width', bodyWidth + 'px');
    var gSubMenus = fnGetSubMenus();
    var gScreenHeight = parseInt($(window).height(),10) - 120;
    $("#_bodyLeft").css("height",gScreenHeight);
    $("#_bodyRight").css("height",gScreenHeight);
    gScreenHeight = parseInt(gScreenHeight,10) - 100;

    fnSetGrid01(gScreenHeight);
    fnGetList01(1);
    fnSetGrid02(300);
    fnGetList02(1);
});

var fnSetGrid01 = function(h) {

    var grdCd = "grid01";

    var widths = [70, 120, 80, 70, 80, 100];
    var titles = ['발행일', '회사명', '금액', '입금일', '담당자', '연락처'];
    var styles = ['text-align:center;', 'text-align:left;', 'text-align:right;', 'text-align:center;','text-align:center;', 'text-align:center;'];

    var gInfo = new Object();
    gInfo["grdCd"] = "grid01";
    gInfo["title"] = "청구서";
    gInfo["widths"] = widths;
    gInfo["titles"] = titles;
    gInfo["styles"] = styles;
    gInfo["function"] = "fnShowInvoice";
    gInfo["fullWidth"] = "500";
    gInfo["fullHeight"] = h;
    gInfo["fix"] = "2";

    G_grid01 = JSON.stringify(gInfo);

    fnMkGridInit(G_grid01);
}

var fnSetGrid02 = function(h) {

    var grdCd = "grid01";

    var widths = [120, 80, 80, 70];
    var titles = ['내역', '금액', '원금', '부가세'];
    var styles = ['text-align:left;', 'text-align:right;', 'text-align:right;','text-align:right;'];

    var gInfo = new Object();
    gInfo["grdCd"] = "grid02";
    gInfo["title"] = "청구 내역";
    gInfo["widths"] = widths;
    gInfo["titles"] = titles;
    gInfo["styles"] = styles;
    //gInfo["function"] = "fnShowInvoice";
    gInfo["fullWidth"] = "290";
    gInfo["fullHeight"] = h;
    gInfo["fix"] = "0";

    G_grid02 = JSON.stringify(gInfo);

    fnMkGridInit(G_grid02);
}

var fnGetList = function() {

    if(event.keyCode != "13")
    {
        return; // 엔터일때만 수행
    }
    fnGetList01(1);
}

var fnGetList01 = function(page) {
    fnMkGridLoad(G_grid01);
    if (page) G_page = page;
    else page = G_page;
    var param  = "findCompany="+$("#findComapny").val();
    var valUrl = "./action/invoice/list.php";

    $.ajax({
        url: valUrl,
        type: 'POST',
        dataType: 'json',
        data: param,
        success: function(data){

            fnMkGrid(G_grid01,data);
            /*
             $("#table_body").html(list);
             $("#total_rows").html(data.TOTAL_ROW_COUNT);
             var paging = fnPaging('fnGetList', data.TOTAL_ROW_COUNT, page, 10);
             var pages = paging['prev'] + paging['pager'] + paging['next'];
             // alert(pages);
             $("#pager").html(pages);
             */
        },
        error: function(data){
            alert('Error!!');
            alert(data.responseText);
        }
    });
}

var fnGetList02 = function(page, invoiceCd) {
    fnMkGridLoad(G_grid02);
    if (page) G_page = page;
    else page = G_page;
    if (invoiceCd == undefined) invoiceCd = -1;
    var param  = "invoiceCd="+invoiceCd;
    var valUrl = "./action/invoice/listIncome.php";

    $.ajax({
        url: valUrl,
        type: 'POST',
        dataType: 'json',
        data: param,
        success: function(data){

            fnMkGrid(G_grid02,data);
            /*
             $("#table_body").html(list);
             $("#total_rows").html(data.TOTAL_ROW_COUNT);
             var paging = fnPaging('fnGetList', data.TOTAL_ROW_COUNT, page, 10);
             var pages = paging['prev'] + paging['pager'] + paging['next'];
             // alert(pages);
             $("#pager").html(pages);
             */
        },
        error: function(data){
            alert('Error!!');
            alert(data.responseText);
        }
    });
}

var fnShowInvoice = function(invoiceCd) {

    var param  = "invoiceCd="+invoiceCd;
    var valUrl = "./action/invoice/view.php";

    $.ajax({
        url: valUrl,
        type: 'POST',
        dataType: 'json',
        data: param,
        success: function(data){
            fnReset();

            var dataDetail = data.TBLINVOICE[0];

            $("#invoiceCd").val(dataDetail.INVOICECD);
            $("#owner").val(dataDetail.OWNER);
            $("#issueDt").val(dataDetail.ISSUEDT);
            $("#amount").val(dataDetail.AMOUNT);
            $("#orgAmount").val(dataDetail.ORGAMOUNT);
            $("#tax").val(dataDetail.TAX);
            $("#incomeDt").val(dataDetail.INCOMEDT);
            $("#major").val(dataDetail.MAJOR);
            $("#majorPhone").val(dataDetail.MAJORPHONE);
            $("#remarks").val(dataDetail.REMARKS);
            $("#flag").val(dataDetail.FLAG);
            setTimeout("fnComboCompany('','"+dataDetail.COMPCD+"','compCd','skip');",500);
            fnGetList02(1,dataDetail.INVOICECD);

        },
        error: function(request,status,error){
            alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
        }
    });
}

var fnSave = function() {
    if (!$("#compCd").val()) {
        alert("회사를 바르게 선택해 주세요.");
        $("#compNm").focus();
        return;
    }
    if (!$("#amount").val()) {
        alert("금액을 바르게 입력해 주세요.");
        $("#amount").focus();
        return;
    }

    if ($("#incomeDt").val()) {
        if (!confirm(" 입금일이 있습니다.\n 자동으로 매출 정산을 진행합니다.\n 이 경우 정산이 완료가 안된 매출건의 경우만\n자동으로 정산을 진행합니다.\n\n 진행하시겠습니까?"))
        return;
    }

    var param = "compCd=" + $("#compCd").val();
    param += "&invoiceCd=" + $("#invoiceCd").val();
    param += "&owner=" + $("#owner").val();
    param += "&issueDt=" + $("#issueDt").val();
    param += "&amount=" + $("#amount").val().split(',').join('');
    param += "&orgAmount=" + $("#orgAmount").val().split(',').join('');
    param += "&tax=" + $("#tax").val().split(',').join('');
    param += "&incomeDt=" + $("#incomeDt").val();
    param += "&major=" + $("#major").val();
    param += "&majorPhone=" + $("#majorPhone").val();
    param += "&remarks=" + $("#remarks").val();
    param += "&flag=" + $("#flag").val();

    var valUrl = "./action/invoice/save.php";

    $.ajax({
        url: valUrl,
        type: 'POST',
        dataType: 'json',
        data: param,
        success: function(data){
            if (data.rsStatus == "Success") {
                alert(data.rsStr);
                fnReset();
                fnGetList01();
            }
            else {
                alert("저장 실패");
            }
        },
        error: function(request,status,error){
            alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
        }
    });
}

var fnReset = function() {

    $("#invoiceCd").val('');
    $("#compCd").val('');
    $("#companyKR").val('');
    $("#owner").val('');
    //$("#issueDt").val('');
    $("#amount").val('');
    $("#orgAmount").val('');
    $("#tax").val('');
    //$("#incomeDt").val('');
    $("#major").val('');
    $("#majorPhone").val('');
    $("#remarks").val('');
    $("#flag").val('Y');
}

var fnPrintInvoice = function() {
    if(!$("#invoiceCd").val()) {
        alert("청구서를 먼저 선택해 주세요");
        return;
    }
    var url = "printExpInvoice.html?inv="+$("#invoiceCd").val();
    window.open(url);
}